package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.orhanobut.logger.Logger;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.CertificationReq;
import com.ydkj.a37e_mall.Classes.Model.Request.IdcardReq;
import com.ydkj.a37e_mall.Classes.Model.Request.TokenReq;
import com.ydkj.a37e_mall.Classes.Model.Request.VerificateCodeReq;
import com.ydkj.a37e_mall.Classes.Model.Response.TokenResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.MyGridView;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static com.loopj.android.http.AsyncHttpClient.log;


/**
 * Created by Administrator on 2017/1/18.
 * 身份认证
 */

public class AuthenticationActivity extends BaseActivity implements View.OnClickListener {
    Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private EditText et_personal_details_material, et_personal_details_id, et_personal_details_paypswd, et_personal_details_paypswd1;
    private ImageView img_back, img_personal_details_state, img_personal_details_state1;

    private MyGridView gridview_store_id_phone;
    private IdCardAdapter idCardAdapter;
    private List<IdcardReq> idcardReqList;
    private ArrayList<String> imagePaths;

    private TextView  tv_verificate_message;
    private RelativeLayout rly_submit, rly_personal_details_state, rly_personal_details_state1;
    private static final int REQUEST_CAMERA_CODE = 11;
    private static final int REQUEST_PREVIEW_CODE = 22;
    private int seekbarnum = 0;
    private long timenum = 1;
    private List<String> path;
    private int code = 0;//判断支付密码的可见隐藏
    private int code1 = 0;
    private int columnWidth;
    private List<String> idcardlist;
    private String idcardstr;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.authenti_cation);
        mActivity = this;
        init();

//        initWindow();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);

    }

    private void init() {
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();
        path = new ArrayList<>();
        idcardlist = new ArrayList<>();
        imagePaths = new ArrayList<>();
        et_personal_details_material = (EditText) mActivity.findViewById(R.id.et_personal_details_material);
        et_personal_details_id = (EditText) mActivity.findViewById(R.id.et_personal_details_id);

        et_personal_details_paypswd = (EditText) mActivity.findViewById(R.id.et_personal_details_paypswd);
        et_personal_details_paypswd1 = (EditText) mActivity.findViewById(R.id.et_personal_details_paypswd1);
        et_personal_details_paypswd.setInputType(InputType.TYPE_CLASS_NUMBER); //输入类型
        et_personal_details_paypswd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)}); //最大输入长度
        et_personal_details_paypswd.setTransformationMethod(PasswordTransformationMethod.getInstance()); //设置为密码输入框
        et_personal_details_paypswd1.setInputType(InputType.TYPE_CLASS_NUMBER); //输入类型
        et_personal_details_paypswd1.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)}); //最大输入长度
        et_personal_details_paypswd1.setTransformationMethod(PasswordTransformationMethod.getInstance()); //设置为密码输入框

        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        img_personal_details_state = (ImageView) mActivity.findViewById(R.id.img_personal_details_state);
        img_personal_details_state1 = (ImageView) mActivity.findViewById(R.id.img_personal_details_state1);

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_verificate_message = (TextView) mActivity.findViewById(R.id.tv_verificate_message);


        rly_submit = (RelativeLayout) mActivity.findViewById(R.id.rly_submit);
        rly_personal_details_state = (RelativeLayout) mActivity.findViewById(R.id.rly_personal_details_state);
        rly_personal_details_state1 = (RelativeLayout) mActivity.findViewById(R.id.rly_personal_details_state1);

        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int columnSpace = getResources().getDimensionPixelOffset(R.dimen.space_size);
        columnWidth = (screenWidth - columnSpace * (cols - 1)) / 2;

        gridview_store_id_phone = (MyGridView) mActivity.findViewById(R.id.gridview_store_id_phone);
        gridview_store_id_phone.setNumColumns(2);

        idcardReqList = new ArrayList<>();
        IdcardReq req = new IdcardReq();
        req.setImgpath("");
        idcardReqList.add(req);

        idCardAdapter = new IdCardAdapter(idcardReqList);
        gridview_store_id_phone.setAdapter(idCardAdapter);

        gridview_store_id_phone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
                if (imagePaths.size() == 2) {

                    PhotoPreviewIntent intent = new PhotoPreviewIntent(mActivity);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                } else {

                    if (position == parent.getChildCount() - 1) {
                        PhotoPickerIntent intent = new PhotoPickerIntent(mActivity);
                        intent.setSelectModel(SelectModel.MULTI);
                        intent.setShowCarema(true); // 是否显示拍照
                        intent.setMaxTotal(2); // 最多选择照片数量，默认为9
                        intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                        startActivityForResult(intent, REQUEST_CAMERA_CODE);
                    } else {
                        PhotoPreviewIntent intent = new PhotoPreviewIntent(mActivity);
                        intent.setCurrentItem(position);
                        intent.setPhotoPaths(imagePaths);
                        startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                    }
                }


            }
        });


        rly_submit.setOnClickListener(this);
        rly_personal_details_state.setOnClickListener(this);
        rly_personal_details_state1.setOnClickListener(this);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {


            case R.id.rly_submit://提交


                if (et_personal_details_material.getText().toString().equals("")) {
                    CommonUtil.showToast(mActivity, "真实姓名不能为空");
                    return;
                }
                if (et_personal_details_id.getText().toString().equals("")) {
                    CommonUtil.showToast(mActivity, "请填写正确的身份证号");
                    return;
                }
                if (et_personal_details_paypswd.getText().toString().equals("") || et_personal_details_paypswd.getText().toString().length() != 6) {
                    CommonUtil.showToast(mActivity, "支付密码不能为空");
                    return;
                }
                if (et_personal_details_paypswd1.getText().toString().equals("") || et_personal_details_paypswd1.getText().toString().length() != 6) {
                    CommonUtil.showToast(mActivity, "确认密码不能为空");
                    return;
                }
                if (!et_personal_details_paypswd.getText().toString().equals(et_personal_details_paypswd1.getText().toString()))
                    if (path.size() == 0) {
                        CommonUtil.showToast(mActivity, "支付密码不一致");
                        return;
                    }



                CustomProgressDialog.createDialog(mActivity).show();
                idcardlist.clear();
                if (imagePaths.size() > 1) {
                    for (int i = 0; i < imagePaths.size(); i++) {
                        Logger.e("ssss", "身份证img ==>" + imagePaths.get(i));
                        GetToken(imagePaths.get(i), "thumb" + imagePaths.get(i).substring(imagePaths.get(i).lastIndexOf("/"), imagePaths.get(i).length()));
                    }

                }


                break;
            case R.id.rly_personal_details_state://支付密码可见隐藏
                if (code == 0) {
                    //如果选中，显示密码
                    et_personal_details_paypswd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    code = 1;
                } else {
                    et_personal_details_paypswd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    code = 0;
                }
                break;
            case R.id.rly_personal_details_state1://支付密码可见隐藏
                if (code1 == 0) {
                    //如果选中，显示密码
                    et_personal_details_paypswd1.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    code1 = 1;
                } else {
                    et_personal_details_paypswd1.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    code1 = 0;
                }
                break;
        }
    }


    //获取七牛的Token
    private void GetToken(final String data, final String key) {
        TokenReq req = new TokenReq();
        req.setType("identifier_pic");
        req.setKey(key);
        try {
            log.e("ssss", "req.getSecret()===>" + req.getstring());
            String source = req.getstring();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
//            log.e("ssss", "secret===>" + secret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = Const.COMMON_ADDRESS + req.urlString();
        params.put("secret", secret);

        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");

                if (errno.equals("000")) {
                    TokenResp resp = GsonImpl.get().toObject(response.toString(), TokenResp.class);
                    PostQiniu(data, key, resp.getResult().getUptoken());
                }
                if (!errno.equals("000")) {
                    CommonUtil.showToast(mActivity, errmsg);

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                log.e("ssss", "statusCode==>" + statusCode);
            }
        });

    }

    private void PostQiniu(String data, String key, String token) {
//        Log.e("ssss", "33333");
//        Log.e("ssss", "data==>" + data);
//        Log.e("ssss", "key==>" + key);
//        Log.e("ssss", "token==>" + token);
        //http上传,指定zone的具体区域
        Configuration config = new Configuration.Builder().zone(Zone.zone2).build();
        UploadManager uploadManager = new UploadManager(config);
//        data = <File对象、或 文件路径、或 字节数组>
//        String key = <指定七牛服务上的文件名，或 null>;
//        String token = <从服务端SDK获取>;
        uploadManager.put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {

                            Log.e("ssss", "上传成功");

                            idcardlist.add(key);
                            idcardstr = CommonUtil.listToString(idcardlist, ',');
                            Log.e(ssss, "idcardstr==>" + CommonUtil.listToString(idcardlist, ','));
                            log.e("ssss", "1111111111==>" + idcardlist.size());
                            log.e("ssss", "2222222222==>" + idcardReqList.size());
                            if (idcardlist.size() == idcardReqList.size()) {
                                log.e("ssss", "33333333333==>" + idcardReqList.size());

                                CustomProgressDialog.Dismiss();
                                Postcertification();
                            }

                        } else {
                            idcardlist.clear();
                            CustomProgressDialog.Dismiss();
                            CommonUtil.showToast(mActivity, "上传失败");
                            Log.e("ssss", "上传失败");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
//                        Log.e("ssss", "res==>" + res);
                    }
                }, null);

    }

    private class IdCardAdapter extends BaseAdapter {
        private List<IdcardReq> idcardList;

        private IdCardAdapter(List<IdcardReq> info) {
            if (info == null) {
                info = new ArrayList<>();
            }
            idcardList = info;
        }

        @Override
        public int getCount() {
            return idcardList.size();
        }

        @Override
        public IdcardReq getItem(int position) {
            return idcardList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            ViewHolder vh = null;
            if (convertView == null) {
                vh = new ViewHolder();
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.store_img_list, null);
                vh.imageView = (ImageView) convertView.findViewById(R.id.imageView11);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
//            log.e("ssss", "imagePaths.size==>" + imagePaths.size());

            if (getItem(position).getImgpath().length() > 0) {
//                Log.e("ssss", "11111");
                Glide.with(mActivity)
                        .load(new File(getItem(position).getImgpath()))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(vh.imageView);
            } else {
//                Log.e("ssss", "加号存在");
                Glide.with(mActivity)
                        .load(new File(getItem(position).getImgpath()))
                        .placeholder(R.mipmap.img_add)
                        .error(R.mipmap.img_add)
                        .centerCrop()
                        .crossFade()
                        .into(vh.imageView);
            }
            return convertView;
        }

        private class ViewHolder {
            ImageView imageView;
        }
    }

    //用户认证
    private void Postcertification() {
        log.e("ssss", "4444444==>" + CommonUtil.listToString(idcardlist, ','));

        CustomProgressDialog.createDialog(mActivity).show();
        CertificationReq req = new CertificationReq();
//        req.setMobile(et_personal_details_telephone.getText().toString());//
//
//        req.setAccount(et_personal_details_bankid.getText().toString());//
//        req.setBank(et_personal_details_bankname.getText().toString());//
        req.setIdentifier_no(et_personal_details_id.getText().toString());//
        req.setPayout_password(et_personal_details_paypswd.getText().toString());
        req.setName(et_personal_details_material.getText().toString());
        req.setIdentifier_pic(CommonUtil.listToString(idcardlist, ','));
//        req.setAddress(myApplication.getProvince2() + myApplication.getCity2() + myApplication.getArea2() + et_detailed_address_street.getText().toString());
        try {
            String source = req.getString();
            Log.e("ssss", "source==>" + source);
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.e("ssss", "uuid==>" + myApplication.getDataEntity().getUuid());
        log.e("ssss", "token==>" + sharedPreferencesUtil.getAccessToken());
        log.e("ssss", "secret==>" + secret);
        params.put("uuid", myApplication.getDataEntity().getUuid());
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", secret);
        AsyncHttpClient httpClient = new AsyncHttpClient();
        httpClient.put(Const.COMMON_ADDRESS + req.urlString() + myApplication.getDataEntity().getUuid(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                log.e("ssss", "response==>" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    finish();
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接异常");
            }
        });
    }

    //获取短信验证码
    public void VerificateCode(String mobile) {
        Log.e("ssss", "mobile==>" + mobile);

        CustomProgressDialog.createDialog(mActivity).show();
        VerificateCodeReq req = new VerificateCodeReq();
        req.setMobile(mobile);
        req.setType("certificate");

        try {
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(req.getSecret());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("ssss", "secret==>" + secret);
        String url = Const.COMMON_ADDRESS + req.urlString();
        Log.e("ssss", "url==>" + url);

        params.put("secret", secret);
        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                Log.e("ssss", "短信==>" + response);
                if (errno.equals("000")) {
                    CommonUtil.showToast(mActivity, errmsg);
                } else {
                    CommonUtil.showToast(mActivity, errmsg);

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("ssss", "22222==>");
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //
                case REQUEST_CAMERA_CODE:
//                    Logger.e("ssss", "列表11111==>" + data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));

                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));

                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
//                    Logger.e("ssss", "列表222222==>" + data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));

                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));

                    break;
            }

        }
    }

    //图片添加 ++++

    private void loadAdpater(List<String> paths) {

        if (imagePaths == null) {
            imagePaths = new ArrayList<>();
        }
        imagePaths.clear();
        imagePaths.addAll(paths);
        if (idcardReqList == null) {
            idcardReqList = new ArrayList<IdcardReq>();
        }

        idcardReqList.clear();
        for (int i = 0; i < imagePaths.size(); i++) {
            IdcardReq idcardReq = new IdcardReq();
//                    Log.e("ssss", "门店缩略图img ==>" + imagePaths.get(i));

            idcardReq.setImgpath(imagePaths.get(i));
            idcardReqList.add(idcardReq);
        }
        if (idcardReqList.size() < 2) {
            IdcardReq req = new IdcardReq();
            req.setImgpath("");
            idcardReqList.add(req);
        }

        if (idCardAdapter == null) {
            idCardAdapter = new IdCardAdapter(idcardReqList);
            gridview_store_id_phone.setAdapter(idCardAdapter);

        } else {

            idCardAdapter.notifyDataSetChanged();
        }
    }
}
